package com.farm.utils_all;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

public class WXPosterUtil {

	public static String createCode() {
		return "";
	}

	public static String getToken() {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APPID
				+ "&secret=" + Constants.SecretKey;
		try {
			JSONObject jsonObject = AuthUtils.doGetJson(url);
			return jsonObject.get("access_token").toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}


	public static String filterEmoji(String nick_name) {
		// nick_name 所获取的用户昵称
		if (nick_name == null || nick_name == "") {
			return nick_name;
		}
		Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
				Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(nick_name);
		if (emojiMatcher.find()) {
			// 将所获取的表情转换为*
			nick_name = emojiMatcher.replaceAll("");
			return nick_name;
		}
		return nick_name;
	}

	public static String decrypt(String encryptedData, String key, String iv) {
		// 被加密的数据
		byte[] dataByte = org.apache.shiro.codec.Base64.decode(encryptedData);
		// 加密秘钥
		byte[] keyByte = org.apache.shiro.codec.Base64.decode(key);
		// 偏移量
		byte[] ivByte = org.apache.shiro.codec.Base64.decode(iv);
		try {
			// 如果密钥不足16位，那么就补足.
			int base = 16;
			if (keyByte.length % base != 0) {
				int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
				byte[] temp = new byte[groups * base];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				/* return JSONObject.parseObject(result); */
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	//首页 商品海报
	public static String createShareWxCode(HttpServletRequest request, Map<String, Object> map) {
		String filePath = "";
		String qiNiuUrl = "";
		try {
			System.out.println("path  : "+request.getSession().getServletContext().getRealPath(""));
			String path = request.getSession().getServletContext().getRealPath("") + "/../upload/wxcode/";
			System.err.println("path  : "+path);
			
		  	File file = new File(path);
	        if (!file.exists()) {
	        	//创建文件夹
	        	System.out.println("不存在,创建");
	            file.mkdirs();
	        }else {
	        	//文件夹存在,不需创建
	        	System.out.println("存在,不用创建");
	        }
			
			
			
			URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + WXPosterUtil.getToken());
			System.out.println(url);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("POST");// 提交模式
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			// 发送请求参数
			JSONObject paramJson = new JSONObject();

			String scene = "";
			
			System.out.println("map : "+map);
			
			if(map.get("agentid") != null && !"".equals(map.get("agentid").toString()) ) {
				scene =  map.get("agentid").toString();
			}
			
			if(map.get("rg_id") != null && !"".equals(map.get("rg_id").toString())) {
				if(!map.get("rg_id").toString().equals("undefined")) {
					scene = scene +"&&"+ map.get("rg_id").toString();
				}
			}else if(map.get("a_id") != null && !"".equals(map.get("a_id").toString())) {
				if(!map.get("a_id").toString().equals("undefined")) {
					scene = scene +"&&"+ map.get("a_id").toString();
				}
			}else if(map.get("t_id") != null && !"".equals(map.get("t_id").toString())) {
				if(!map.get("t_id").toString().equals("undefined")) {
					scene = scene +"&&"+ map.get("t_id").toString();
				}
				
			}
			System.out.println("scene   : "+scene);
			paramJson.put("scene",scene);
		
			System.out.println(paramJson.get("scene"));

			qiNiuUrl = img(map, path, httpURLConnection, printWriter, paramJson);
			System.out.println("qiNiuUrl  :  "+qiNiuUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return qiNiuUrl;

	}

	private static String img(Map<String, Object> map, String path, HttpURLConnection httpURLConnection,
			PrintWriter printWriter, JSONObject paramJson) throws IOException, FileNotFoundException {
		String filePath;
		String qiNiuUrl;
		paramJson.put("page", map.get("page"));

		paramJson.put("width", "430");
		paramJson.put("auto_color", true);
		paramJson.put("is_hyaline", true);
		System.out.println(paramJson);
		printWriter.write(paramJson.toString());
		// flush输出流的缓冲
		printWriter.flush();
		// 开始获取数据

		BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String fileAdd = sdf.format(new Date());
		// 获取文件夹路径
		File file1 = new File(path + "/" + fileAdd);
		// File file1 = new File("D:/xcxm");
		System.out.println(path + "/" + fileAdd);
		System.out.println(file1.getPath());
		// 如果文件夹不存在则创建
		if (!file1.exists() && !file1.isDirectory()) {
			file1.mkdir();
		}
		String fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + ".png";
		filePath = file1.getCanonicalPath() + "/" + fileName;
		File wxCodefile = new File(filePath);
		OutputStream os = new FileOutputStream(wxCodefile);
		int len;
		byte[] arr = new byte[1024];
		while ((len = bis.read(arr)) != -1) {
			os.write(arr, 0, len);
			os.flush();
		}
		os.close();
		qiNiuUrl = wxCodefile.getCanonicalPath().replace("/www/wwwroot/", "https://");
		return qiNiuUrl;
	}

	private static String img(String path, HttpURLConnection httpURLConnection, PrintWriter printWriter,
			JSONObject paramJson) throws IOException, FileNotFoundException {
		String filePath;
		String qiNiuUrl;
		printWriter.write(paramJson.toString());
		// flush输出流的缓冲
		printWriter.flush();
		// 开始获取数据

		BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+08"));
		String fileAdd = sdf.format(new Date());
		// 获取文件夹路径
		File file1 = new File(path + "/" + fileAdd);
		// 如果文件夹不存在则创建
		if (!file1.exists() && !file1.isDirectory()) {
			file1.mkdir();
		}
		String fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + ".png";
		filePath = file1.getCanonicalPath() + "/" + fileName;
		File wxCodefile = new File(filePath);
		OutputStream os = new FileOutputStream(wxCodefile);
		int len;
		byte[] arr = new byte[1024];
		while ((len = bis.read(arr)) != -1) {
			os.write(arr, 0, len);
			os.flush();
		}
		os.close();
		qiNiuUrl = wxCodefile.getCanonicalPath().replace("/www/wwwroot/", "https://");
		return qiNiuUrl;
	}

}
